package com.business.wechat.handler;

import java.util.Map;

import com.business.wechat.bean.WxUserBean;

import org.springframework.stereotype.Component;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import net.sf.rose.jdbc.dao.BeanDAO;
import net.sf.rose.jdbc.query.BeanSQL;
import net.sf.rose.jdbc.service.Service;

/**
 * 用户关注公众号Handler
 * <p>
 * Created by FirenzesEagle on 2016/7/27 0027. Email:liumingbo2008@gmail.com
 */
@Component
public class UnSubscribeHandler extends AbstractHandler {

	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
			WxSessionManager sessionManager) throws WxErrorException {
		WxMpUser wxMpUser = weixinService.getMpService().getUserService().userInfo(wxMessage.getFromUser(), "zh_CN");
		Service service = new Service();
		try {
			String openId = wxMessage.getFromUser();
			BeanDAO dao = new BeanDAO(service);
			BeanSQL query = dao.getQuerySQL();
			WxUserBean user = new WxUserBean();
			user.setOpenId(openId);
			user.setSubscribe(WxUserBean.SUBSCRIBED_NO);
			query.createUpdateSql(user);
			dao.update();
			service.commit();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			service.close();
		}
		WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content("尊敬的" + wxMpUser.getNickname() + "您好，欢迎再来！\n")
				.fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
		return m;
	}
}
